package com.example.demo.heima.reactor;

import org.apache.ibatis.annotations.SelectKey;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname Acceptor
 * @description 主Reactor
 * @date 2023/08/12 16:09
 * <p>
 * ******************************************************
 */
public class Acceptor extends ServerThead{

    private final Server server;

    private final ServerSocketChannel serverSocketChannel;

    private final Collection<PollerIO> ioThreads;

    private Iterator<PollerIO> ioIterator;

    public Acceptor(String name, Server server, Set<PollerIO> ioThreads) throws IOException {
        super(name);
        this.server = server;
        this.serverSocketChannel = ServerSocketChannel.open();
        // bind port
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.bind(new InetSocketAddress(server.getPort()));
        // register to selector
        this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);

        this.ioThreads = Collections.unmodifiableCollection(ioThreads);
        this.ioIterator = this.ioThreads.iterator();
    }

    @Override
    public void run() {
        super.run();
        if (!server.stopped && !this.serverSocketChannel.socket().isClosed()) {
            try {
                this.selector.select();
                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if (!selectionKey.isValid()) {
                        continue;
                    }
                    if (selectionKey.isAcceptable()) {
                        doAccept(selectionKey);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void doAccept(SelectionKey selectionKey) throws IOException {
        SocketChannel socketChannel = this.serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        // get pollerIO,than register to selector
        if (!ioIterator.hasNext()) {
            this.ioIterator = this.ioThreads.iterator();
        }
        PollerIO pollerIO = ioIterator.next();
        //
        pollerIO.addAcceptedConnection(socketChannel);
    }
}
